package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.SqlServer;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import bean.Pergunta;
import bean.Usuario;

/**
 * Servlet implementation class Perguntas
 */
@WebServlet(name = "ServletPerguntas", urlPatterns = { "/ServletPerguntas" })
public class Perguntas extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SqlServer dao = new SqlServer();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Perguntas() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("caralho");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStreamReader inputStream = new InputStreamReader( request.getInputStream() ); 
		BufferedReader reader = new BufferedReader( inputStream );
		String entrada = reader.readLine();
		
		//Transformando a leitura da resposta para interpreta��o via JSON
		JSONObject jsonReq = JSONObject.fromObject( entrada  );
		//Capturando o valor enviado
		String usuario;
		
		usuario = jsonReq.getString("usuario");			
		
						
		JSONArray jsonResp = new JSONArray();				
		
		for (Pergunta pe : dao.getPerguntas()) {
			HashMap<String,String> dadosRetorno = new HashMap<String,String>();
			dadosRetorno.put("id", pe.getId()+"");
			dadosRetorno.put( "pergunta", pe.getPergunta());
			dadosRetorno.put("resposta", pe.getResposta());
			dadosRetorno.put("alternativas", pe.getAlternativas());
			dadosRetorno.put("foto", pe.getFoto());
			JSONObject jo = JSONObject.fromObject(dadosRetorno);
			jsonResp.add(jo);
			
		}
//		System.out.println("Total recebido do dao "+dao.getPerguntas().size());
		response.setContentType("application/json");
		
		PrintWriter out = response.getWriter();
		out.print( jsonResp );
		out.flush();
	}

}
